import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {Globals} from "../../../globals";
import {ApiUrl} from "../../../config/api-url";
import {BaseService} from "../../../shared/service/base.service";
import {PageHelper} from "../../../utils/page-helper-model";
import {MyDateModel} from '../../../models/my-date.model';
import {Consts} from '../../../config/consts';
import {Observable} from 'rxjs';
import {ActivatedRoute} from "@angular/router";
import {RoleIdEnum} from '../../../enums/role-id.enum';

@Component({
  selector: 'app-stock-statistic',
  templateUrl: './stock-statistic.component.html',
  styleUrls: ['./stock-statistic.component.less']
})
export class StockStatisticComponent implements OnInit {

  formModel: FormGroup;
  isMobile = Globals.isMobile();
  // 门店
  merchantStoreList: Array<{ value: string; label: string }> = [];
  groupTypeList: Array<{ value: number; label: string }> = [];
  // 机构
  agencyList: [];
  // 运营商
  userList: [];
  listOfData: any;
  commodityStockRecord: any;
  // commodityStockRecord = {
  //   totalProfit: 0,
  //   totalRetailPrice: 0,
  //   totalCostPrice: 0,
  //   totalQuantity: 0,
  // };
  pageHelper: PageHelper = new PageHelper;
  type = 1;
  // 开始日期类型
  startDateTimeType = 'start';
  // 结束日期类型
  endDateTimeType = 'end';
  // 开始日期
  startDateTime: Date;
  // 结束日期
  endDateTime: Date;
  userInfo: any;
  day = 'primary';
  month = 'default';
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
  };

  constructor(private fb: FormBuilder, public baseService: BaseService, private route: ActivatedRoute) {
    this.buildForm();

    this.route.params.subscribe(params => {
      if (params['secondaryType'] != null) {
        let secondaryType = params['secondaryType'];
        this.formModel.get('secondaryType').setValue(secondaryType);
        console.log('secondaryType', secondaryType);
      }
    });
  }
  disabledHours(): number[] {
    return [1, 2, 3];
  }
  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.startDateTime = this.baseService.zorro.getDateTime().startYesterday;
    this.endDateTime = this.baseService.zorro.getDateTime().endYesterday;
    this.initGroupTypeList()
    this.getAllUserOfName();
    this.getAllAgencyOfName();
    this.findAllMerchantStoreByUserInfo();
    this.findData();
    this.statsHeadCommodityStock();

  }
  initGroupTypeList(){
    this.groupTypeList = [
      { value: 1, label: '商品分组' },
      { value: 2, label: '设备分组' },
      { value: 3, label: '场地分组' }
    ];
  }
  buildForm() {
    this.formModel = this.fb.group({
      merchantStoreIdArray: [[], []],
      dateType: ['1', []],
      userId: ['', []],
      createTime: [null, []],
      updateTime: [null, []],
      agencyId: ['', []],
      deviceNo: [null, []],
      commodityName: [null, []],
      secondaryType: ['-1', []],
      groupTypeIdArray: [[1, 3], []],
      orderId: ['1', []],
    });
  }
  submitForm() {
    this.pageHelper.currentPage = 1;
    this.statsHeadCommodityStock();
    this.findData();
  }

  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }
  onPageSizeChange(pageSize: any){
    // console.log(pageSize, 'pageSize');
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.findData();
  }
  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.findData();
  }
  gainAgencyId($event: any) {
    this.getAllUserOfName();
  }
  statsHeadCommodityStock(){
    if (this.startDateTime == null || this.endDateTime == null) {
      this.baseService.layer.messageError('请选择订单时间!');
      return null;
    }
    this.formModel.get('createTime').setValue(this.startDateTime);
    this.formModel.get('updateTime').setValue(this.endDateTime);
    this.formModel.get('dateType').setValue(this.type);
    if (this.formModel.get('createTime').value > this.formModel.get('updateTime').value){
      this.baseService.layer.messageError('开始时间不能大于结束时间');
      return;
    }
    if (this.formModel.get('groupTypeIdArray').value == null || this.formModel.get('groupTypeIdArray').value.length <= 0){
      this.baseService.layer.messageError('最少选择一个分组');
      return;
    }
    this.baseService.post(ApiUrl.CommodityStockRecordUrl + '/stockStatistic', this.formModel.value).subscribe(
      item => {
        if (item.status == 0) {
          this.commodityStockRecord = item.data.data;
        } else {
          this.baseService.layer.messageError(item.msg);
        }
      }
    );
  }

  // 数据导出
  exportCsv() {
    if (this.startDateTime == null || this.endDateTime == null) {
      this.baseService.layer.messageError('请选择订单时间!');
      return null;
    }
    if(this.formModel.get('groupTypeIdArray').value == null || this.formModel.get('groupTypeIdArray').value.length <= 0){
      this.baseService.layer.messageError('最少选择一个分组');
      return;
    }
    this.baseService.layer.modalConfirm('确定导出数据吗？', confirm => {
      if (confirm) {
        this.formModel.get('createTime').setValue(this.startDateTime);
        this.formModel.get('updateTime').setValue(this.endDateTime);
        this.formModel.get('dateType').setValue(this.type);
        this.baseService.post(ApiUrl. CommodityStockRecordUrl + '/exportStockStatistic/list', this.formModel.value).subscribe(
          res => {
            // console.log('数据导出返回值', res);
            if (res.status == 0) {
              this.export(res.data.downloadUrl, res.data.fileName);
            } else {
              this.baseService.layer.messageError(res.msg);
            }
          }
        );
      }
    });
  }
  // Blob文件转换下载
  export(url: any, fileName: string, fileType?: any) {
    this.requestBlob(url, {}).subscribe(result => {
      this.downFile(
        result,
        fileName,
        fileType ||
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
    });
  }
  requestBlob(url: any, data?: any): Observable<any> {
    return this.baseService.http.request('post', url, {
      body: data,
      observe: 'response',
      responseType: 'blob',
    });
  }
  downFile(result, fileName, fileType?) {
    const data = result.body;
    const blob = new Blob([data], {type: fileType || data.type});
    const objectUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.setAttribute('style', 'display:none');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', fileName);
    a.click();
    URL.revokeObjectURL(objectUrl);
  }
  findData() {
    this.formModel.get('createTime').setValue(this.startDateTime);
    this.formModel.get('updateTime').setValue(this.endDateTime);
    this.formModel.get('dateType').setValue(this.type);
    if(this.formModel.get('createTime').value > this.formModel.get('updateTime').value){
      this.baseService.layer.messageError('开始时间不能大于结束时间');
      return
    }
    if(this.formModel.get('groupTypeIdArray').value == null || this.formModel.get('groupTypeIdArray').value.length <= 0){
      this.baseService.layer.messageError('最少选择一个分组');
      return;
    }
    this.baseService.findListByMuchCondition(ApiUrl.CommodityStockRecordUrl + '/stockStatisticList', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          this.pageHelper.totalItems = data.data.total;
          this.listOfData = data.data.list;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
  getAllUserOfName() {
    let agencyId = this.formModel.get('agencyId').value;
    if (agencyId == null) {
      agencyId = '0';
    }
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=' + agencyId).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }


  gainUserId($event: any) {
    this.findAllMerchantStoreByUserInfo();
  }

// 将开始、结束时间往外抛
  outDateTime($event: MyDateModel) {
    /**
     * date: Fri Mar 19 2021 23:59:06 GMT+0800 (中国标准时间) {}
     * type: "end"
     */
    if ($event.type == 'start') {
      this.startDateTime = $event.date;
    } else if ($event.type == 'end') {
      this.endDateTime = $event.date;
    }
  }
  onStartMonth($event) {
    this.startDateTime = $event;
  }

  onEndMonth($event: any) {
    this.endDateTime = $event;
  }
  dayMethod() {
    this.startDateTime = this.baseService.zorro.getDateTime().startYesterday;
    this.endDateTime = this.baseService.zorro.getDateTime().endYesterday;
    this.pageHelper.currentPage = 1;
    this.type = 1;
    this.day = 'primary';
    this.month = 'default';
    this.findData();
  }

  monthMethod() {
    this.startDateTime = this.baseService.zorro.getDateTime().startLastMonth;
    this.endDateTime = this.baseService.zorro.getDateTime().endLastMonth;
    this.pageHelper.currentPage = 1;
    this.type = 2;
    this.day = 'default';
    this.month = 'primary';
    this.findData();
    console.log('type',this.type);
  }
  findAllMerchantStoreByUserInfo() {
    let userId = this.formModel.get('userId').value;
    if (userId == null) {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data.map(item => ({
            value: item.id,
            label: item.storeName
          }));
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }


}
